﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.ViewModel;
using DunSilverlight.Comm;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Text;
using System.IO;
using Telerik.Windows.Controls;

namespace DunSilverlight.Views
{
    public partial class WordPage : Page
    {
        ReportService.ReportServiceClient ser = new ReportService.ReportServiceClient();
        BankService.BankServiceClient bankSer = new BankService.BankServiceClient();
        UserService.UserServiceClient userSer = new UserService.UserServiceClient();
        public WordPage()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Report_Word))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent(); 
            
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";
            

            bankSer.GetListByHQLCompleted += new EventHandler<BankService.GetListByHQLCompletedEventArgs>(bankSer_GetListByHQLCompleted);
            loadBank();

            userSer.GetListBySQLCompleted += new EventHandler<UserService.GetListBySQLCompletedEventArgs>(userSer_GetListBySQLCompleted);
            loadOper();

            ser.WordPageCompleted += new EventHandler<ReportService.WordPageCompletedEventArgs>(ser_WordPageCompleted);

            ser.GetCallCountCompleted += new EventHandler<ReportService.GetCallCountCompletedEventArgs>(ser_GetCallCountCompleted);

            ser.GetDunRecordListCompleted += new EventHandler<ReportService.GetDunRecordListCompletedEventArgs>(ser_GetDunRecordListCompleted);
        }

        /// <summary>
        /// 读取银行list
        /// </summary>
        private void loadBank()
        {
            bankSer.GetListByHQLAsync("From Company");
        }

        // <summary>
        /// 读取操作员list（用权限判断）
        /// </summary>
        private void loadOper()
        {
            string orgNumber = AppGlobal.CurrentUser.Organization.FullNumber;
            string orgChildNumber = orgNumber + ".%";
            //获取当前机构下的操作员（具有催收权限）
            string sql = string.Format(
                        @" select u.Id,u.Name
                            from User_User as u 
                            left join User_Role as r on u.RoleId=r.Id
                            left join Organization_Organization org on u.OrganizationId = org.Id
                            where 
                                u.isused=1  and 
                                (org.FullNumber like '{0}' or org.FullNumber = '{1}') and 
                                exists(select 1 from User_Role_Right as rr 
                                            inner join User_Right as ur on rr.RightId=ur.Id 
                                        where ur.Number='process_case' and
                                rr.RoleId=r.Id) ", orgChildNumber, orgNumber);

            userSer.GetListBySQLAsync(sql);
        }

        IList<DunLibrary.Client.Company> bankList;
        void bankSer_GetListByHQLCompleted(object sender, BankService.GetListByHQLCompletedEventArgs e)
        {
            int total = 0;
            bankList = JsonSerializerHelper.JsonToEntities<DunLibrary.Client.Company>(e.Result, out total);
            //取出银行分类（非支行）
            cboxBank.ItemsSource = bankList;

        }

        void userSer_GetListBySQLCompleted(object sender, UserService.GetListBySQLCompletedEventArgs e)
        {
            int total = 0;
            var objList = JsonSerializerHelper.JsonToEntities<object[]>(e.Result, out total);
            List<UserModel> userList = objList.Select(c => new UserModel
            {
                Id = int.Parse(c[0].ToString()),
                Name = c[1].ToString()
            }).ToList();

            cboxOper.ItemsSource = userList;

            if (AppGlobal.CurrentUser.Role.Name == "业务员")
            {
                var item = userList.SingleOrDefault(c => c.Id == AppGlobal.CurrentUser.Id);
                if (item != null)
                {
                    cboxOper.SelectedItem = item;
                    cboxOper.IsEnabled = false;
                }
            }
        }


        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (timePeriod.SelectedDate == null)
            {
                Tools.ShowMessage("请选择数据期号!", "", false);
                return;
            }

            if (tbIdCard.Value != null && !string.IsNullOrEmpty(tbIdCard.Value.ToString()))
            {
                string NumericOrLetter = "^[A-Za-z0-9]+$";
                if (!Regex.IsMatch(tbIdCard.Value.ToString(), NumericOrLetter))
                {
                    Tools.ShowMessage("‘身份证号码’输入格式错误!", "只能输入数字和字母!", false);
                    tbIdCard.Value = null;
                    return;
                }
            }

            if (cboxOper.SelectedItem == null && !string.IsNullOrEmpty(cboxOper.Text))
            {
                Tools.ShowMessage("任务负责人输入错误!", "", false);
                return;
            }

            if (cboxBank.SelectedItem == null && !string.IsNullOrEmpty(cboxBank.Text))
            {
                Tools.ShowMessage("银行分类输入错误!", "", false);
                return;
            }


            DateTime selected = timePeriod.SelectedDate.Value;
            int period = int.Parse(selected.ToString("yyyyMM"));


            int? import = null;
            if (timeImport.SelectedDate != null)
                import = int.Parse(timeImport.SelectedDate.Value.ToString("yyyyMMdd"));


            string arrealDiffStart = null;
            if (delayStart.Value != null)
                arrealDiffStart = delayStart.Value.ToString();

            string arrealDiffEnd = null;
            if (delayEnd.Value != null)
                arrealDiffEnd = delayEnd.Value.ToString();

            double? arrealAmountStart = null;
            if (amountStart.Value != null)
            {
                double val = double.Parse(amountStart.Value.ToString());
                if (val > 0.0)
                    arrealAmountStart = val;
            }

            double? arrealAmountEnd = null;
            if (amountEnd.Value != null)
            {
                double val = double.Parse(amountEnd.Value.ToString());
                if (val > 0.0)
                    arrealAmountEnd = val;
            }

            if (arrealAmountStart != null && arrealAmountEnd != null)
            {
                if (arrealAmountEnd < arrealAmountStart)
                {
                    Tools.ShowMessage("‘欠费金额’输入错误!", "最大金额必须大于最小金额!", false);
                    amountStart.Value = amountEnd.Value = null;
                    amountStart.Focus();
                    return;
                }
            }

            int? operId = null;
            if (cboxOper.SelectedItem != null)
                operId = int.Parse(cboxOper.SelectedValue.ToString());

            string cardNo = null;
            if (tbCardNo.Value != null)
                cardNo = tbCardNo.Value.ToString();

            string holderName = null;
            if (tbName.Value != null)
                holderName = tbName.Value.ToString();

            string idCard = null;
            if (tbIdCard.Value != null)
                idCard = tbIdCard.Value.ToString();

            int? bankId = null;
            if (cboxBank.SelectedItem != null)
                bankId = (cboxBank.SelectedItem as DunLibrary.Client.Company).Id;
            
            string orgNum = null;
            if (AppGlobal.CurrentUser.Organization != null)
                orgNum = AppGlobal.CurrentUser.Organization.FullNumber;
            Tools.ShowMask(true);
            ser.WordPageAsync(period,import,arrealDiffStart,arrealDiffEnd, arrealAmountStart, arrealAmountEnd, operId, cardNo, holderName,
                idCard, bankId, orgNum);

        }


        void ser_WordPageCompleted(object sender, ReportService.WordPageCompletedEventArgs e)
        {
            int total = 0;
            var list = JsonSerializerHelper.JsonToEntities<DunLibrary.Report.WordPage>(e.Result, out total);
            RadGridView1.ItemsSource = list;
            Tools.ShowMask(false);
        }

        /// <summary>
        /// 重置所有查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            timePeriod.SelectedDate = DateTime.Now;
            timePeriod.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM";

            delayStart.Value = delayEnd.Value = null;

            amountStart.Value = amountEnd.Value = null;

            if (cboxOper.SelectedItem != null)
                cboxOper.SelectedItem = null;
            else
                cboxOper.Text = null;

            tbCardNo.Value = null;
            tbName.Value = null;
            tbIdCard.Value = null;

            if (cboxBank.SelectedItem != null)
                cboxBank.SelectedItem = null;
            else
                cboxBank.Text = null;


            RadGridView1.ItemsSource = null;
        }

        

        private void allSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.SelectAll();
        }

        private void noneSelect_Click(object sender, RoutedEventArgs e)
        {
            RadGridView1.UnselectAll();
        }

        bool? res1 = false;
        SaveFileDialog dialog1 = null;
        private void layerPaper_Click(object sender, RoutedEventArgs e)
        {
            if (RadGridView1.SelectedItems.Count == 0)
            {
                Tools.ShowMessage("请选择要生成‘律师函’的记录", "", false);
                return;
            }

            string extension = "doc";

            string selectedItem = "Word";

            dialog1 = new SaveFileDialog();
            dialog1.DefaultExt = extension;
            dialog1.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, selectedItem);

            dialog1.FilterIndex = 1;
            res1 = dialog1.ShowDialog();

            if (res1 == true)
            {
                var list = new List<DunLibrary.Report.WordPage>();
                foreach (var item in RadGridView1.SelectedItems)
                {
                    list.Add(item as DunLibrary.Report.WordPage);
                }

                string cardIdListStr = string.Join(",", list.Select(c => c.CardId));
                List<string> yearPeriodList = new List<string>();
                foreach (var word in list)
                {
                    yearPeriodList.Add(word.YearPeriod.ToString());

                }
                string yearPeriodListStr = string.Join(";", yearPeriodList);

                ser.GetCallCountAsync(cardIdListStr, yearPeriodListStr,list);
            }

        }

        void ser_GetCallCountCompleted(object sender, ReportService.GetCallCountCompletedEventArgs e)
        {
            var countList = e.Result.Split(',').ToList();

            var list = e.UserState as List<DunLibrary.Report.WordPage>;

            Assembly assembly = GetType().Assembly;

            string html = string.Empty;
            using (System.IO.Stream htmlStream = assembly.GetManifestResourceStream("DunSilverlight.Template.LayerPaper.htm"))
            {
                byte[] bsHtml = new byte[htmlStream.Length];
                htmlStream.Read(bsHtml, 0, (int)htmlStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                html = Encoding.UTF8.GetString(bsHtml, len, bsHtml.Length - len);
            }
            string entityList = generateReport(list, countList);
            html = html.Replace("@t_entityList", entityList);

            using (Stream stream = dialog1.OpenFile())
            {
                byte[] bs = Encoding.UTF8.GetBytes(html);
                string a = Encoding.UTF8.GetString(bs, 0, bs.Length);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
            }
        }

        /// <summary>
        /// 生成报告
        /// </summary>
        private string generateReport(List<DunLibrary.Report.WordPage> list, List<string> countList)
        {
            Assembly assembly = GetType().Assembly;

            string htmlTemplate = string.Empty;
            using (System.IO.Stream htmlStream = assembly.GetManifestResourceStream("DunSilverlight.Template.LayerPaperEntity.htm"))
            {
                byte[] bsEntity = new byte[htmlStream.Length];
                htmlStream.Read(bsEntity, 0, (int)htmlStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                htmlTemplate = Encoding.UTF8.GetString(bsEntity, len, bsEntity.Length - len);
            }
            List<string> strList = new List<string>();
            for (int i = 0; i < list.Count;i++ )
            {
                var item = list[i];
                DateTime now = DateTime.Now;
                string html = htmlTemplate;
                html = html.Replace("@t_year", now.Year.ToString());
                html = html.Replace("@t_holderName", item.HolderName);
                html = html.Replace("@t_cardNo", item.CardNo);
                html = html.Replace("@t_date", now.ToString("yyyy年MM月dd日"));
                html = html.Replace("@t_amountNotPay", item.TotalSub.ToString());
                html = html.Replace("@t_callCount", countList[i].ToString());
                html = html.Replace("@t_diff", item.CardDelayLevel);
                html = html.Replace("@layerName", AppGlobal.CurrentUser.Name);
                
                strList.Add(html);
            }

            string br = "<span lang=\"EN-US\" style=\"font-size: 12.0pt; line-height: 150%; font-family: &quot;Times New Roman&quot;,&quot;serif&quot;\"><br clear=\"all\" style=\"page-break-before: always\"></span>";
            string entityList = string.Join(br, strList);

            return entityList;
        }

        bool? res2 = false;
        SaveFileDialog dialog2 = null;
        private void receivePaper_Click(object sender, RoutedEventArgs e)
        {
            if (RadGridView1.SelectedItems.Count == 0)
            {
                Tools.ShowMessage("请选择要生成‘催收记录’的记录", "", false);
                return;
            }

            string extension = "doc";

            string selectedItem = "Word";

            dialog2 = new SaveFileDialog();
            dialog2.DefaultExt = extension;
            dialog2.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, selectedItem);

            dialog2.FilterIndex = 1;
            res2 = dialog2.ShowDialog();

            if (res2 == true)
            {
                var word = RadGridView1.SelectedItems[0] as DunLibrary.Report.WordPage;
                
                ser.GetDunRecordListAsync(word.ArId, word);
            }
        }

        void ser_GetDunRecordListCompleted(object sender, ReportService.GetDunRecordListCompletedEventArgs e)
        {
            int total = 0;
            var callRecords = JsonSerializerHelper.JsonToEntities<DunLibrary.Report.DunRecord>(e.Result, out total);

            Assembly assembly = GetType().Assembly;

            string html = string.Empty;
            using (System.IO.Stream htmlStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunRecord.htm"))
            {
                byte[] htmlbs = new byte[htmlStream.Length];
                htmlStream.Read(htmlbs, 0, (int)htmlStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                html = Encoding.UTF8.GetString(htmlbs, len, htmlbs.Length - len);
            }

            string entityHtml = string.Empty;
            using (System.IO.Stream entityStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunRecordEntity.htm"))
            {
                byte[] entitybs = new byte[entityStream.Length];
                entityStream.Read(entitybs, 0, (int)entityStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                entityHtml = Encoding.UTF8.GetString(entitybs, len, entitybs.Length - len);
            }

            string detailHtml = string.Empty;
            using (System.IO.Stream detailStream = assembly.GetManifestResourceStream("DunSilverlight.Template.DunRecordDetail.htm"))
            {
                byte[] detailbs = new byte[detailStream.Length];
                detailStream.Read(detailbs, 0, (int)detailStream.Length);
                int len = 0;// Encoding.UTF8.GetPreamble().Length;
                detailHtml = Encoding.UTF8.GetString(detailbs, len, detailbs.Length - len);
            }

            string line = "<div style=\"mso-element: para-border-div; border: none; border-bottom: solid windowtext 3.0pt; padding: 0cm 0cm 1.0pt 0cm; margin-left: 42.0pt; margin-right: 0cm\">"
                           + "<p align=\"left\" class=\"MsoListParagraph\" style=\"text-align: left; text-indent: 0cm; mso-char-indent-count: 0; line-height: 150%; mso-pagination: widow-orphan; border: none; mso-border-bottom-alt: solid windowtext 3.0pt; padding: 0cm; mso-padding-alt: 0cm 0cm 1.0pt 0cm\">"
                           + " <span style=\"font-size: 12.0pt; line-height: 150%; font-family: 宋体; mso-bidi-font-family: 宋体; color: black; mso-font-kerning: 0pt\">"
                           + " <span lang=\"EN-US\"><o:p></o:p></span></span></p>"
                           + "</div>";

            var item = e.UserState as DunLibrary.Report.WordPage;

            var q = from i in callRecords
                    group i by new  //因为这几个字段都来自于arrear，所以可以group
                    {
                        YearPeriod = i.YearPeriod,
                        TotalArrear = i.TotalArrear,
                        TotalReturn = i.TotalReturn,
                        CardDelayLevel = i.CardDelayLevel,
                        Currency = i.Currency
                    }
                        into g
                        select g;
                    
            StringBuilder sbEntity = new StringBuilder();
            if (total > 0)
            {
                sbEntity.Append(line);
                foreach (var itemGroups in q.OrderByDescending(c => c.Key.YearPeriod))
                {
                    string entity = entityHtml;
                    entity = entity.Replace("@t_bankName", item.BankName);
                    entity = entity.Replace("@t_cardNo", item.CardNo);
                    entity = entity.Replace("@t_number", "");
                    entity = entity.Replace("@t_cardDelayLevel", itemGroups.Key.CardDelayLevel);
                    entity = entity.Replace("@t_amountArreal", itemGroups.Key.TotalArrear.ToString());
                    entity = entity.Replace("@t_amountReturn", itemGroups.Key.TotalReturn.ToString());
                    entity = entity.Replace("@t_currency", itemGroups.Key.Currency);
                    DateTime date = new DateTime(itemGroups.Key.YearPeriod / 100, itemGroups.Key.YearPeriod % 100, 1);
                    entity = entity.Replace("@t_date", date.ToString("yyyy年MM月"));



                    StringBuilder sbDetail = new StringBuilder();
                    foreach (var detail in itemGroups.OrderBy(c => c.CallTime))
                    {
                        string detailStr = detailHtml;
                        detailStr = detailStr.Replace("@t_date", detail.CallTime == null ? "" : detail.CallTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));
                        detailStr = detailStr.Replace("@t_operName", item.OperName);
                        detailStr = detailStr.Replace("@t_Type", detail.ReceiveType);
                        detailStr = detailStr.Replace("@t_Description", detail.CallContent);
                        sbDetail.Append(detailStr);
                    }
                    sbEntity.Append(entity.Replace("@t_details", sbDetail.ToString()));
                }
                sbEntity.Append(line);
            }

            html = html.Replace("@t_body", sbEntity.ToString());

            using (Stream stream = dialog2.OpenFile())
            {
                byte[] bs = Encoding.UTF8.GetBytes(html);
                string a = Encoding.UTF8.GetString(bs, 0, bs.Length);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
            }
        }

        private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnQuery_Click(sender, null);
            }
        }
    }
}
